package com.superb.allocation.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.aliyun.oss.model.ObjectMetadata;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.superb.allocation.utils.AliyunOssUtils;
import com.superb.common.core.annotation.SuperbDataScope;
import com.superb.common.core.annotation.SuperbRestMapping;
import com.superb.common.core.model.Result;
import com.superb.common.utils.HeardersUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件存储;(allocation_file)表控制层
 * @Author: ajie
 * @CreateTime: 2024-7-4
 */
@SuperbDataScope
@SuperbRestMapping("/file")
@Tag(name = "文件存储接口")
@ApiSupport(author = "阿杰：ajie20999@163.com")
public class AllocationFileController {

    @PostMapping("upload")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "文件上传", parameters = {
            @Parameter(name = "dir", description = "存到存储空间中的路径默认存在default文件夹下，以天分割开", in = ParameterIn.HEADER),
            @Parameter(name = "bucket", description = "存到哪个存储空间：默认zlgyl", in = ParameterIn.HEADER),
            @Parameter(name = "auth", description = "文件是否授权，true为私有需授权访问，false为公共读任何人（包括匿名访问者）都可以对该文件进行读操作", in = ParameterIn.HEADER),
            @Parameter(name = "isCover", description = "文件是否覆盖，true当文件重复时，直接覆盖图片(重命名)，false时则直接返回已存在图片的key", in = ParameterIn.HEADER),
    })
    public Result<String> upload(@RequestBody MultipartFile file) throws IOException {
        // 获取该文件是否为公共文件
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType(file.getContentType());
        meta.setContentLength(file.getSize());
        // 校验存储空间是否存在
        Map<String, String> userMeta = new HashMap<>();
        // 操作人
        try {
            // 创建人
            userMeta.put("createBy", StpUtil.getLoginId().toString());
            // 创建部门
            userMeta.put("organId", HeardersUtils.getOrganId());
        } catch (Exception ignored) {}
        // 上传时间
        userMeta.put("createTime", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        meta.setUserMetadata(userMeta);
        String upload = AliyunOssUtils.upload().upload(file.getInputStream(), meta, file.getOriginalFilename());
        return Result.success("上传成功！", upload);
    }

    @GetMapping("url")
    public Result<String> getUrl(@RequestParam("key") String key) {
        return Result.success("", AliyunOssUtils.getUrl(key));
    }

    @GetMapping("view")
    public void view(@RequestParam("key") String key, HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        AliyunOssUtils.view(key, response.getOutputStream());
    }

    @GetMapping("delete")
    public Result<Boolean> delete(@RequestParam("key") String key) {
        if (AliyunOssUtils.upload().delete(key)) {
            return Result.success();
        }
        return Result.error();
    }
}